package cc.sheji.util;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

import static org.springframework.data.redis.serializer.RedisSerializationContext.string;

@Component
public class HttpUtil {

    private OkHttpClient client = null;
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @PostConstruct
    public void init() {
//        client = new OkHttpClient.Builder()
//                .readTimeout(10000, TimeUnit.MILLISECONDS)
//                .connectTimeout(10000, TimeUnit.MILLISECONDS)
//                .writeTimeout(10000, TimeUnit.MILLISECONDS)
//                .build();
       client = new OkHttpClient().newBuilder().connectTimeout(100000, TimeUnit.MILLISECONDS)
                .readTimeout(60000, TimeUnit.MILLISECONDS)
                .build();
        log.info("初始化Okhttp");
    }

    public void getToString(String url, Map<String, String> headers, final StateCallBack back) {


        Request.Builder builder = new Request.Builder()
                .url(url).get();
        if (headers != null)
            headers.forEach(new BiConsumer<String, String>() {
                @Override
                public void accept(String key, String value) {
                    builder.header(key, value);
                }
            });
        client.newCall(builder.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (back == null)
                    return;
                if (e != null) {
                    back.onFail(e.toString());
                } else {
                    back.onFail("请求失败");
                }

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (back == null)
                    return;
                try {
                    if (response != null) {
                        ResponseBody body = response.body();
                        if (body != null) {
                            try {

                                String data = body.string();

                                back.onSuccess(data);
                                return;
                            } catch (Exception e) {
                                System.out.println("null exception 22");
                                e.printStackTrace();
                            }

                        }
                    }
                } catch (Throwable throwable) {
                    System.out.println("请求出错位置2");
                    throwable.printStackTrace();
                }
                back.onFail("请求失败");
            }
        });
    }
//    public void getToString(String url, Map<String, String> headers, final StateCallBack back) {
//
//
//        Request.Builder builder = new Request.Builder()
//                .url(url).get();
//        if (headers != null)
//            headers.forEach(new BiConsumer<String, String>() {
//                @Override
//                public void accept(String key, String value) {
//                    builder.header(key, value);
//                }
//            });
//        client.newCall(builder.build()).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                if (back == null)
//                    return;
//                if (e != null) {
//                    back.onFail(e.toString());
//                } else {
//                    back.onFail("请求失败");
//                }
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                if (back == null)
//                    return;
//                try {
//                    if (response != null) {
//                        ResponseBody body = response.body();
//                        if (body != null) {
//                            try {
//
//                                String data = body.string();
//
//                                back.onSuccess(data);
//                                return;
//                            } catch (Exception e) {
//                                System.out.println("null exception 22");
//                                e.printStackTrace();
//                            }
//
//                        }
//                    }
//                } catch (Throwable throwable) {
//                    System.out.println("请求出错位置2");
//                    throwable.printStackTrace();
//                }
//                back.onFail("请求失败");
//            }
//        });
//    }
    public void postJsonToString(String url, String jsonstr, Map<String, String> headers, final StateCallBack back) {

        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, jsonstr);
        Request.Builder builder = new Request.Builder()
                .url(url)
                .post(requestBody);
        if (headers != null)
            headers.forEach(new BiConsumer<String, String>() {
                @Override
                public void accept(String key, String value) {
                    builder.header(key, value);
                }
            });
        client.newCall(builder.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (back == null)
                    return;
                if (e != null) {
                    back.onFail(e.toString());
                } else {
                    back.onFail("请求失败1");
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (back == null)
                    return;
                try {
                    if (response != null) {
                        ResponseBody body = response.body();
                        if (body != null) {
                            try {
                                String data = body.string();
                                back.onSuccess(data);
                                return;
                            } catch (Exception e) {
                                System.out.println("null exception 22");
                                System.out.println(response.toString());
                                e.printStackTrace();
                            }

                        }
                    }
                } catch (Throwable throwable) {
                    System.out.println("请求出错位置2");
                    throwable.printStackTrace();
                }
                back.onFail(response.toString());

            }
        });
    }
    public String postJson(String url, String jsonstr, Map<String, String> headers) throws IOException {

        MediaType JSON = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON, jsonstr);
        Request.Builder builder = new Request.Builder()
                .url(url)

                .post(requestBody);
        if (headers != null)
            headers.forEach(new BiConsumer<String, String>() {
                @Override
                public void accept(String key, String value) {
                    builder.header(key, value);
                }
            });
        Response response=client.newCall(builder.build()).execute();
        try {
            if (response != null) {
                ResponseBody body = response.body();
                if (body != null) {
                    try {
                        String data = body.string();
                        return data;
                    } catch (Exception e) {
                        System.out.println("null exception 22");
                        e.printStackTrace();
                        return "";
                    }

                }
            }
        } catch (Throwable throwable) {
            System.out.println("请求出错位置2");
            throwable.printStackTrace();
            return "";
        }
        return "";
    }
    public String downloadImage(String url, String updataPath) {
        try {
            Request request = new Request.Builder()
                    //访问路径
                    .url(url)
                    .build();
            Response response = null;
            response = client.newCall(request).execute();
            if (response != null&&response.isSuccessful()) {
                ResponseBody body = response.body();
                if (body != null) {
                    byte[] bytes = body.bytes();
                    String[] split = url.split("\\.");
                    //本地文件夹目录（下载位置）
                    String name = System.currentTimeMillis() + ".jpg";
                    if (split != null && split.length > 0) {
                        name = System.currentTimeMillis() + "." + split[split.length - 1];
                    }
                    File file = new File(updataPath, name);
                    BufferedOutputStream out = FileUtil.getOutputStream(file);
                    out.write(bytes);
                    out.flush();
                    out.close();
                    return file.getAbsolutePath();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public String updataFile(String url, String fileName) throws Exception {

        File file = new File(fileName);
        //使用MultipartBody上传多个文件，Builder构建着
        MultipartBody multipartBody = new MultipartBody.Builder()
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();

        Request request = new Request.Builder().url(url).post(multipartBody).build();
        Call call = client.newCall(request);
        if (call == null)
            return null;
        Response execute = call.execute();
        if (execute != null) {
            ResponseBody body = execute.body();
            if (body != null) {
                String result = body.string();
                return result;
            }
        }
        return null;
    }


    public String getToString(String url) {

        try {

            Request request = new Request.Builder()
                    //访问路径
                    .url(url)
                    .build();
            Response response = null;
            response = client.newCall(request).execute();
            if (response != null) {
                ResponseBody body = response.body();
                if (body != null) {
                    String json = body.string();
                    return json;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getLocation(String url) {
        if (url == null)
            return null;

        try {
            Request request = new Request.Builder()
                    //访问路径
                    .url(url)
                    .build();
            Response response = null;
            response = client.newCall(request).execute();
            if (response != null ) {

                //System.out.println("content11:xxx");
                String content = response.networkResponse().toString();
               // System.out.println("content:"+content);
                if (content != null) {
                    int i = content.indexOf("url=");
                    if(i>0){
                        if(content.length()>i+4){
                            content = content.substring(i+4, content.length() - 1);
                            return content;
                        }
                    }
                }
                try {
                    response.close();
                }catch (Exception e){
                    System.out.println("close  location error");
                    e.printStackTrace();
                }

            }
            System.out.println("fail query location");
        } catch (Exception e) {
            System.out.println("net error");
            e.printStackTrace();
        }
        return null;
    }


}
